﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;

using Telerik.WinControls;
using Telerik.WinControls.UI;
using System.IO;
using Aspose.Cells;

namespace UnigenReport.Form
{
    public partial class ucProduct : UserControl
    {
        private UnigenDataContext db;

        #region Thiết lập

        public ucProduct()
        {
            InitializeComponent();
            //Phân quyền
            if (Variables.UserRoleID == 0)
            {
                btnDelete.Visibility =
                btnImport.Visibility =
                btnExportTemp.Visibility = ElementVisibility.Collapsed;
            }
            SetEvent();
            Common.SetMenuShortcut(btnInsert, btnUpdate, btnDelete, btnGetData, btnCloseForm);
        }

        /// <summary>
        /// Khai báo các sự kiện
        /// </summary>
        private void SetEvent()
        {
            this.Load += OnLoad;
            this.btnInsert.Click += new System.EventHandler(this.btnInsert_Click);
            this.btnUpdate.Click += new System.EventHandler(this.btnUpdate_Click);
            this.btnDelete.Click += new System.EventHandler(this.btnDelete_Click);
            this.btnGetData.Click += new System.EventHandler(this.btnGetData_Click);
            this.btnImport.Click += new System.EventHandler(this.btnImport_Click);
            this.btnExportTemp.Click += new System.EventHandler(this.btnExportTemp_Click);
            this.btnCloseForm.Click += new System.EventHandler(this.btnCloseForm_Click);
            this.btnSaveImport.Click += new System.EventHandler(this.btnSaveImport_Click);
            this.btnCancelImport.Click += new System.EventHandler(this.btnCancelImport_Click);
            this.btnSearch.Click += new System.EventHandler(this.btnSearch_Click);
            this.btnExport.Click += new System.EventHandler(this.btnExport_Click);
            this.btnPrint.Click += new System.EventHandler(this.btnPrint_Click);
            this.btnExportData.Click += new System.EventHandler(this.btnExportData_Click);
            this.grvProduct.CellDoubleClick += new Telerik.WinControls.UI.GridViewCellEventHandler(this.grvProduct_CellDoubleClick);        
        }

        /// <summary>
        /// Hàm load form
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void OnLoad(object sender, EventArgs e)
        {
            //Load default
            SetDefault();
        }

        /// <summary>
        /// Thiết lập các giá trị mặc định của form
        /// </summary>
        private void SetDefault()
        {
            //Source unit
            db = new UnigenDataContext();
            sourceUnit.DataSource = db.Units.OrderBy(p=>p.UnitName);

            //Bind dữ liệu chính
            BindData();
        }

        /// <summary>
        /// Lấy dữ liệu chính
        /// </summary>
        private void BindData()
        {
            //Data bind
            sourceProduct.DataSource = GetData();

            //STT
            Common.SetNo(grvProduct);
        }

        private List<Product> GetData()
        {
            db = new UnigenDataContext();
            var productName = txtProductName.Text.Trim();
            return db.Products.Where(p => p.Active == true
                && (!String.IsNullOrEmpty(productName) ? 
                (
                    p.ProductCode.Contains(productName)
                    || p.ProductName.Contains(productName)
                    || p.ProductNameVi.Contains(productName)
                ) : 1 == 1)
                ).OrderBy(p => p.ProductName).ToList();
        }

        private void SetImportState(bool isImport)
        {
            if (isImport)
            {
                cmbImport.Visibility = ElementVisibility.Visible;
                cmbMenu.Enabled = btnSearch.Enabled = txtProductName.Enabled = false;
                grvProduct.CellDoubleClick -= grvProduct_CellDoubleClick;
            }
            else
            {
                cmbImport.Visibility = ElementVisibility.Collapsed;
                cmbMenu.Enabled = btnSearch.Enabled = txtProductName.Enabled = true;
                grvProduct.CellDoubleClick += grvProduct_CellDoubleClick;
            }
        }

        #endregion

        #region Hàm

        private void Insert()
        {
            try
            {
                var newProduct = new Form.ucProductEdit() { Dock = DockStyle.Fill };
                var ui = Common.CreateForm(newProduct, String.Empty, 460, 390);

                if (ui.ShowDialog() == DialogResult.OK)
                {
                    BindData();
                    Common.ShowSaveSuccess();
                }
            }
            catch (Exception ex)
            {
                Common.ShowErrorMess("Insert - " + ex.Message);
            }
        }

        private void Update()
        {
            try
            {
                if (sourceProduct.Current == null)
                {
                    Common.ShowSelectionRequire();
                    return;
                }

                var p = sourceProduct.Current as Product;

                var productEdit = new Form.ucProductEdit() { Dock = DockStyle.Fill }.ForUpdate(p);
                var ui = Common.CreateForm(productEdit, String.Empty, 460, 390);

                if (ui.ShowDialog() == DialogResult.OK)
                {
                    BindData();
                    Common.ShowSaveSuccess();
                }
            }
            catch (Exception ex)
            {
                Common.ShowErrorMess("Update - " + ex.Message);
            }
        }

        private void Delete()
        {
            try
            {
                if(Common.ShowQuestion("Xóa mặt hàng này?") != DialogResult.OK)
                    return;

                if (sourceProduct.Current == null)
                {
                    Common.ShowSelectionRequire();
                    return;
                }

                db = new UnigenDataContext();
                var inputProduct = (sourceProduct.Current as Product);
                var deleteProduct = db.Products.SingleOrDefault(p => p.ProductId == inputProduct.ProductId);
                //Xóa
                db.Products.DeleteOnSubmit(deleteProduct);
                db.SubmitChanges();

                //Remove khỏi grid
                sourceProduct.Remove(inputProduct);
                Common.SetNo(grvProduct);

                //Thông báo
                Common.ShowSaveSuccess();
            }
            catch (Exception ex)
            {
                Common.ShowErrorMess("Delete - " + ex.Message);
            }
        }

        private void ExportFile(List<Product> data, string fileName, int exportType)
        {
            try
            {
                //datacontext
                db = new UnigenDataContext();

                //Tạo một đối tượng workbook
                var stream = new MemoryStream(global::UnigenReport.Properties.Resources.ProductReport);
                var workbook = new Workbook(stream);

                var cells = workbook.Worksheets[0].Cells;
                var rowIndex = 2;

                if (data.Count > 1)
                    cells.InsertRows(2, data.Count - 1);

                //Bắt đầu đổ dữ liệu
                for (var i = 0; i < data.Count; i++)
                {
                    var item = data[i];

                    //Cột STT
                    cells["A" + rowIndex].PutValue(i + 1);
                    cells["B" + rowIndex].PutValue(item.ProductCode);
                    cells["C" + rowIndex].PutValue(item.ProductName);
                    cells["D" + rowIndex].PutValue(item.ProductNameVi);
                    cells["E" + rowIndex].PutValue(item.Cost);
                    cells["F" + rowIndex].PutValue(item.UhanCodeUsing);

                    rowIndex++;
                }

                try
                {
                    workbook.Save(fileName);

                    //Mở file Excel vừa lưu
                    if (exportType == 0) //Xuất excel
                    {
                        System.Diagnostics.Process.Start(fileName);
                    }
                    else //In
                    {
                        var config = new SystemConfig.UserConfig();
                        Common.PrintExcelAuto(fileName, config.PrintCopies);
                    }
                }
                catch (Exception ex)
                {
                    Common.ShowErrorMess("ExportFile - " + ex.Message);
                    return;
                }
            }
            catch (Exception ex)
            {
                Common.ShowErrorMess("ExportFile - " + ex.Message);
                return;
            }
        }

        #endregion

        #region Sự kiện

        protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
        {
            if (keyData == Keys.Enter)
            {
                BindData();
            }
            return base.ProcessCmdKey(ref msg, keyData);
        }

        private void btnInsert_Click(object sender, EventArgs e)
        {
            Insert();
        }

        private void btnUpdate_Click(object sender, EventArgs e)
        {
            Update();
        }

        private void btnDelete_Click(object sender, EventArgs e)
        {
            Delete();
        }

        private void btnGetData_Click(object sender, EventArgs e)
        {
            BindData();
        }

        private void btnImport_Click(object sender, EventArgs e)
        {
            //Chon file
            var openFileDialog = new OpenFileDialog();

            if (openFileDialog.ShowDialog() != DialogResult.OK)
            {
                return;
            }

            if (openFileDialog.FileName.Equals(String.Empty))
            {
                return;
            }

            var fileName = openFileDialog.FileName;

            //Import
            var workbook = new Workbook(fileName);
            var woCells = workbook.Worksheets[0].Cells;

            var lstImportProduct = new List<Product>();
            var success = true;
            var row = 2;
            var error = String.Empty;
            while (woCells["B" + row].Value != null)
            {
                var product = new Product();
                product.ProductCode = (woCells["B" + row].Value ?? "").ToString();
                if (String.IsNullOrEmpty(product.ProductCode) || db.Products.Count(p => p.ProductCode == product.ProductCode) > 0 || lstImportProduct.Count(p => p.ProductCode == product.ProductCode) > 0)
                {
                    error = "Mã " + product.ProductCode + " đã tồn tại trong hệ thống hoặc trùng trong file";
                    success = false;
                    break;
                }
                product.ProductName = (woCells["C" + row].Value ?? "").ToString();
                product.ProductNameVi = (woCells["D" + row].Value ?? "").ToString();
                var unit = db.Units.SingleOrDefault(p => p.UnitName == (woCells["E" + row].Value ?? "").ToString());
                if (unit == null)
                {
                    error = "Đơn vị " + (woCells["E" + row].Value ?? "").ToString() + " (dòng " + row + ")  không tồn tại";
                    success = false;
                    break;
                }
                //wo.ProductId = product.ProductId;
                product.Unit = unit;
                decimal cost = 0;
                decimal salePrice = 0;
                decimal.TryParse((woCells["F" + row].Value ?? "").ToString(), out cost);
                decimal.TryParse((woCells["G" + row].Value ?? "").ToString().ToString(), out salePrice);
                product.Cost = cost;
                product.SalePrice = salePrice;
                product.HSCode = (woCells["H" + row].Value ?? "").ToString();
                product.UhanCodeUsing = (woCells["I" + row].Value ?? "").ToString();
                product.Active = true;

                //Add to list
                lstImportProduct.Add(product);

                row++;
            }
            if (!success)
            {
                Common.ShowErrorMess(error);
            }
            else
            {
                SetImportState(true);
                sourceProduct.Clear();
                sourceProduct.DataSource = lstImportProduct;
                Common.SetNo(grvProduct);
            }
        }

        private void btnExportTemp_Click(object sender, EventArgs e)
        {
            //Xuat file
            var saveFileDialog = new SaveFileDialog
            {
                FileName = "ProductTemplate.xls"
            };

            if (saveFileDialog.ShowDialog() != DialogResult.OK)
            {
                return;
            }

            if (saveFileDialog.FileName.Equals(String.Empty))
            {
                return;
            }

            var fileName = saveFileDialog.FileName;

            //Mở file template cần đổ dữ liệu vào
            var stream = new MemoryStream(global::UnigenReport.Properties.Resources.ProductTemplate);
            //Tạo một đối tượng workbook
            var workbook = new Workbook(stream);

            db = new UnigenDataContext();
            var cells = workbook.Worksheets[1].Cells;
            var unit = db.Units.OrderBy(p => p.UnitName).ToList();
            var index = 2;
            foreach (var item in unit)
            {
                cells["A" + index].Value = item.UnitName;

                index++;
            }
            workbook.Save(fileName);

            //Mở file Excel vừa lưu
            System.Diagnostics.Process.Start(fileName);
        }

        private void btnCloseForm_Click(object sender, EventArgs e)
        {
            (this.Parent as Telerik.WinControls.UI.RadPageViewPage).Dispose();
        }

        private void btnSaveImport_Click(object sender, EventArgs e)
        {
            if (sourceProduct.Count == 0)
            {
                Common.ShowNoticeMess("Không có dữ liệu mới!");
                SetImportState(false);
                BindData();
                return;
            }
            db = new UnigenDataContext();
            foreach (var item in (sourceProduct.DataSource as List<Product>))
                db.Products.InsertOnSubmit(item.Clone());

            db.SubmitChanges();
            BindData();
            //menu
            SetImportState(false);
        }

        private void btnCancelImport_Click(object sender, EventArgs e)
        {
            BindData();
            //menu
            SetImportState(false);
        }
        
        private void btnSearch_Click(object sender, EventArgs e)
        {
            BindData();
        }

        private void btnExport_Click(object sender, EventArgs e)
        {
            var source = GetData();
            if (source.Count == 0) return;

            //Xuat file
            var saveFileDialog = new SaveFileDialog
            {
                FileName = String.Format("ListProduct{0}.xls", DateTime.Now.ToString("yyyyMMddHHmmss"))
            };

            if (saveFileDialog.ShowDialog() != DialogResult.OK)
            {
                return;
            }

            if (saveFileDialog.FileName.Equals(String.Empty))
            {
                return;
            }

            var fileName = saveFileDialog.FileName;
            ExportFile(source, fileName, 0);
        }

        private void btnPrint_Click(object sender, EventArgs e)
        {
            var source = GetData();
            if (source.Count == 0) return;

            var dir = "Temp";
            if (!System.IO.File.Exists(dir))
                System.IO.Directory.CreateDirectory(dir);
            var fileName = String.Format("ListProduct{0}.xls", DateTime.Now.ToString("yyyyMMddHHmmss"));
            ExportFile(source, dir + "\\" + fileName, 1);
        }

        private void btnExportData_Click(object sender, EventArgs e)
        {
            //Xuat file
            var saveFileDialog = new SaveFileDialog
            {
                FileName = String.Format("MasterList{0}.xls", DateTime.Now.ToString("yyyyMMddHHmmss"))
            };

            if (saveFileDialog.ShowDialog() != DialogResult.OK)
            {
                return;
            }

            if (saveFileDialog.FileName.Equals(String.Empty))
            {
                return;
            }

            var fileName = saveFileDialog.FileName;

            //Mở file template cần đổ dữ liệu vào
            var stream = new MemoryStream(global::UnigenReport.Properties.Resources.MasterListTemplate);
            //Tạo một đối tượng workbook
            var workbook = new Workbook(stream);

            db = new UnigenDataContext();

            //Product
            workbook.Worksheets[0].Cells.ImportCustomObjects(db.Products.ToList(), new string[]{"ProductId",
	            "ProductCode",
	            "ProductName",
	            "ProductNameVi",
	            "UnitId",
	            "Cost",
	            "SalePrice",
	            "HSCode",
	            "UhanCodeUsing",
	            "Active"}, true, 0, 0, db.Products.Count(), false, "dd/MM/yyyy", false);

            //packing standard
            workbook.Worksheets[1].Cells.ImportCustomObjects(db.PackingStandards.ToList(), new string[]{"PackingId",
	            "ProductId",
	            "QtyPerInnerBox",
	            "WeightOfInnerBox",
	            "QtyPerShippingBox",
	            "WeightOfShippingBox",
	            "CartonTypeId",
	            "Active"}, true, 0, 0, db.PackingStandards.Count(), false, "dd/MM/yyyy", false);

            //Carrton types
            workbook.Worksheets[2].Cells.ImportCustomObjects(db.CartonTypes.ToList(), new string[]{"CartonTypeId",
	            "Dimension"}, true, 0, 0, db.CartonTypes.Count(), false, "dd/MM/yyyy", false);

            //pallet standard
            workbook.Worksheets[3].Cells.ImportCustomObjects(db.PalletStandards.ToList(), new string[]{"PalletId",
	            "CartonTypeId",
	            "QtyPerPallet",
	            "PalletWeight",
	            "Dimension"}, true, 0, 0, db.PalletStandards.Count(), false, "dd/MM/yyyy", false);
            workbook.Save(fileName);

            //Mở file Excel vừa lưu
            System.Diagnostics.Process.Start(fileName);
        }
        
        private void grvProduct_CellDoubleClick(object sender, GridViewCellEventArgs e)
        {
            Update();
        }

        #endregion
    }
}
